package com.h3c.nem.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author chenyifan
 * @date 2022/6/10 15:00
 */
@Slf4j
public class EncryptionUtil {

    private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    /**
     * 密钥
     */
    private static final String KEY = "8tpvol47bhg7pyrc";

    /**
     * 根据KEY生成AES
     */
    private static AES aes =
            new AES(Mode.ECB, Padding.ZeroPadding,
                    SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(), KEY.getBytes()).getEncoded());

    /**
     * 获取加密后信息
     *
     * @param plainText 明文
     * @return 加密后信息
     */
    public static String getEncryptDataAES(String plainText) {
        return aes.encryptHex(plainText);
    }

    /**
     * 获取解密后信息
     *
     * @param cipherText 密文
     * @return 解密后信息
     */
    public static String getDecryptDataAES(String cipherText) {
        return aes.decryptStr(cipherText);
    }

    /**
     * 校验密码是否正确
     *
     * @param password     待校验密码
     * @param realPassword 正确密码
     * @return
     */
    public static Boolean match(String password, String realPassword) {
        return encoder.matches(password, realPassword);
    }

    /**
     * 密码加密
     *
     * @param password 密码
     * @return
     */
    public static String encode(String password) {
        return encoder.encode(password);
    }

    /**
     * 对北森和sap同步的员工初始化密码
     *
     * @param certNo
     * @return
     */
    public static String encodeForBeiSenAndSap(String certNo) {
        String passWord = "H3C" + StrUtil.sub(certNo, -4, certNo.length());
        return encode(passWord);
    }
}
